﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[AddComponentMenu("TagMachine/Entity/Wolf")]
public class Wolf : MonoBehaviour 
{
	public float BaseSpeedModifier			= 0.9f;

	public string FugitiveTrailTag 			= "FugitiveTrail";
	public float TrailSpeedModifier			= 0.1f;
	public float TrailSpeedRemain			= 1.0f;

	private MovingEntity m_MovingComponent 	= null;
	
	private List< Fugitive > m_OnFugitiveTrails = new List<Fugitive> ();
	private List< float > m_OnFugitiveTrailsTime = new List<float> ();

	void Awake()
	{
		m_MovingComponent 	= transform.parent.GetComponent< MovingEntity > ();
	}

	public void Activate()
	{
		m_OnFugitiveTrails.Clear();
		m_OnFugitiveTrailsTime.Clear();

		// Update character controller radius
		if ( m_MovingComponent != null )
		{
			m_MovingComponent.UpdateSpeed( BaseSpeedModifier );
			m_MovingComponent.UpdateSize( collider as CapsuleCollider );
			m_MovingComponent.enabled = true;
		}

		gameObject.SetActive( true );
	}

	void Update() 
	{
		for ( int i = 0; i < m_OnFugitiveTrailsTime.Count; ++i )
		{
			m_OnFugitiveTrailsTime[i] -= Time.deltaTime;

			if ( m_OnFugitiveTrailsTime[i] <= 0.0f )
			{
				m_OnFugitiveTrails.RemoveAt( i );
				m_OnFugitiveTrailsTime.RemoveAt( i );
				--i;
			}
		}

		m_MovingComponent.UpdateSpeed( BaseSpeedModifier + m_OnFugitiveTrails.Count * TrailSpeedModifier );
	}

	void OnTriggerEnter( Collider _Collider )
	{
		if ( _Collider.CompareTag( FugitiveTrailTag ) )
		{
			Fugitive FugitiveComp = _Collider.GetComponent< EntityTrail >().Parent;

			int IndexOfFugitive = m_OnFugitiveTrails.IndexOf(FugitiveComp);
			if ( IndexOfFugitive == -1 )
			{
				m_OnFugitiveTrails.Add( FugitiveComp );
				m_OnFugitiveTrailsTime.Add( TrailSpeedRemain );
			}
			else
			{
				m_OnFugitiveTrailsTime[IndexOfFugitive] = TrailSpeedRemain;
			}
		}
	}
}
